package com.nullpointer.playerinfo.common.objects;

import java.time.Duration;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisPubSub;

public class Correspond {

    private JedisPool subscribePool;
    private JedisPool publishPool;
    private JedisPubSub pubSub;
    private String channel;
    private int serverCode;
    
    public Correspond(String host, int port, int serverCode) {
        this.serverCode = serverCode;
        this.subscribePool = new JedisPool(host, port);
        this.publishPool =new JedisPool(host, port);
        this.channel = "playerInfo";

        JedisPoolConfig config = new JedisPoolConfig();
        config.setTestOnBorrow(true); //获取连接时检查有效性
        config.setTestOnReturn(true); //返还连接时检查有效性
        config.setTestWhileIdle(true); //空闲时检查有效性
        config.setTimeBetweenEvictionRuns(Duration.ofSeconds(30)); //每30秒检查一次
        config.setMinEvictableIdleDuration(Duration.ofMinutes(5)); //连接空闲5分钟被驱逐
        config.setNumTestsPerEvictionRun(-1); //每次检查所有连接
        config.setMaxTotal(10);
        config.setMaxIdle(3);
        config.setMinIdle(1);
        config.setMaxWait(Duration.ofSeconds(1));
        this.publishPool =new JedisPool(config, host, port);
    }

    public void start() {
        this.pubSub = new JedisPubSub() {
            @Override
            public void onMessage(String channel, String message) {
                if (!message.startsWith(String.valueOf(Correspond.this.serverCode)) && channel.equals(Correspond.this.channel)) {
                    handleMessage(message);
                }
            }
        };
        try (Jedis jedis = subscribePool.getResource()) {
            jedis.subscribe(pubSub, Correspond.this.channel);
        }
    }

    public void handleMessage(String message) {}

    public void sendMessage(String message) {
        try (Jedis jedis = publishPool.getResource()) {
            jedis.publish(this.channel, serverCode + " " + message);
        }
    }
}
